<?php

namespace app\admin\controller;

use app\model\AdminModel;
use Respect\Validation\Validator;
use support\Request;

class PublicController
{
    //获取图形验证码
    public function captcha(Request $request)
    {
        $img_content = get_captcha('admin_captcha');

        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    public function login(Request $request)
    {
        if (get_admin_id()) {
            return redirect('/admin/index/index');
        }

        if(is_post()){
            try {
                $data = Validator::input($request->post(), [
                    'account' => Validator::alnum()->length(1, 200)->setName('用户名'),
                    'password' => Validator::length(1, 64)->setName('密码'),
                    'captcha' => Validator::length(1, 6)->setName('验证码'),
                ]);
            } catch (\Throwable $e) {
                return error($e->getMessage());
            }

            if (strtolower($data['captcha']) !== $request->session()->get('admin_captcha')) {
                return error('验证码错误');
            }

            $model = new AdminModel();

            $admin = $model->field('id,account,password,status')->where("account",$data['account'])->find();

            if(empty($admin)) return error("用户不存在或密码错误!");
            if(get_password($data['password']) !== $admin['password']) return error("用户不存在或密码错误!");
            if($admin['status'] != '1') return error("用户被禁用!");

            $admin->last_login_time = time();
            $admin->last_login_ip = $request->getRealIp(true);
            $admin->save();

            $request->session()->delete('admin_captcha');

            $request->session()->set('admin_id',$admin['id']);

            return success("登录成功");
        }

        return view('login');
    }

}
